package chapter15.validate;

import chapter15.pojo.Transaction;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-04-20 上午10:43
 */
public class TransactionValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        // 判断验证是否为Transaction,如果是则进行验证
        return Transaction.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        Transaction trans = (Transaction) o;
        // 求交易金额和价格x数量的差额
        double dis = trans.getPrice() * trans.getQuantity() - trans.getAmount();
        // 判断是否误差大小
        if (Math.abs(dis) > 0.01) {
            // 加入错误信息
            errors.rejectValue("amount", null, "交易金额与购买数量和价格不匹配");
        }
    }
}
